/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { SyntaxKind, TypeNode, TypeReferenceNode } from 'ts-morph';
import { PropertyKind, TypeStructure, SerializerMetadata } from '../Types';
import { BaseTypeHandler } from './BaseTypeHandler';
import { TypeContext, ConversionDirection, ITypeHandler } from './ITypeHandler';

class DateHandler extends BaseTypeHandler implements ITypeHandler {
    readonly name: string = 'DateHandler';
    kind: PropertyKind = PropertyKind.Date;
    priority: number = 95;
    matches(typeNode: TypeNode, context: TypeContext): boolean {
        if (typeNode.getKind() === SyntaxKind.TypeReference) {
            const typeRef = typeNode as TypeReferenceNode;
            const refName = typeRef.getTypeName().getText();
            return refName === 'Date';
        }
        return false;
    }
    parse(typeNode: TypeNode, context: TypeContext): TypeStructure {
        return {
            kind: PropertyKind.Date,
            depth: 0,
            sourceText: typeNode.getText(),
            args: [],
            dependencies: []
        };
    }
    getSerializerMetadata(structure: TypeStructure, withParam?: string): SerializerMetadata {
        return {
            name: 'DateSerializer',
            typeDeclaration: 'DateSerializer',
            instantiationTemplate: 'DateSerializer.INSTANCE',
            encodeMethod: 'encodeSerializableElement',
            decodeMethod: 'deserialize',
            decoderType: 'Date | undefined',
            needsTypeAssertion: false
        };
    }
    generateInstantiation(structure: TypeStructure): string {
        return 'DateSerializer.INSTANCE';
    }
    generateTypeDeclaration(structure: TypeStructure): string {
        return 'DateSerializer';
    }
    generateTypeKey(structure: TypeStructure): string {
        return structure.sourceText;
    }
    generateSendableTypeDeclaration(structure: TypeStructure): string {
        return structure.sourceText;
    }
    generatePropertyConversion(structure: TypeStructure, sourceValue: string, direction: ConversionDirection): string {
        return sourceValue;
    }
}

/**
 * 工厂函数
 */
export function createDateHandler(): ITypeHandler {
    return new DateHandler();
}